import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { iframeTaskMitt } from '@/utils/tools/bus'
import { getBasketQuestion, postAddTask } from '@/apis/assignment/index'

export const useTaskStore = defineStore(
  'task',
  () => {
    // 用于同步多个tab试题篮数据
    const broadcastChannel = ref()
    const createBroadcastChannel = () => {
      broadcastChannel.value = new BroadcastChannel('question-basket-broadcast')
      broadcastChannel.value.onmessage = e => {
        if (e.data.type === 'basket') {
          getBasketQuestionInfo()
        }
      }
    }

    const postMessage = () => {
      broadcastChannel.value.postMessage({ type: 'basket' })
    }

    const destroyBroadcastChannel = () => {
      broadcastChannel.value = null
    }

    // 1-课程任务 2-习题任务 4-错题任务

    // 结构 {source subject_id topic_id topic_type is_similar relation_id question_detaiL score_strategy totalScore score subScore}
    // source:题目来源 subject_id:题目科目 topic_id:题目id topic_type：题型 is_similar:是否是举一反三题目（是-1） relation_id：举一反三原题id（不是举一反三传0）question_detail：题目详情
    // score_strategy 评分策略  totalScore 单题/大题分数
    // subScore [] 小题数组 {score score_strategy} 分数 得分策略
    const taskList = ref([])

    const getTransTask = question => {
      console.log(question)
      return {
        ...question,
        totalScore: 0,
        score_strategy: 0,
        subScore: (question.question_detail?.subproblem || []).map(item => ({
          id: item.id,
          score: 0,
          score_strategy: 0
        }))
      }
    }
    const setTaskList = (listItem, isPatch = false) => {
      // 因为不想改别人的代码所以这么写
      if (listItem.length) {
        listItem = listItem.map(item => getTransTask(item))
      } else {
        listItem = getTransTask(listItem)
      }
      // 批量增加，一般是举一反三的题目
      if (isPatch) {
        listItem.forEach(question => {
          if (
            taskList.value.findIndex(
              item => item.topic_id === question.topic_id
            ) === -1
          ) {
            taskList.value.push(question)
          }
        })
      } else {
        if (
          taskList.value.length &&
          taskList.value.findIndex(
            item => item.topic_id === listItem.topic_id
          ) !== -1
        ) {
          ElMessage.error('重复添加')
          return
        } else {
          taskList.value.push(listItem)
        }
      }
      ElMessage.success('添加习题成功')
      postAddTaskInfo()
    }

    const onDeleteTopic = type => {
      const removeList = taskList.value.filter(item => item.topic_type === type)
      const list = taskList.value.filter(item => item.topic_type !== type)

      taskList.value = list
      postAddTaskInfo()
      iframeTaskMitt.emit('delete-topic', removeList)
    }

    const deleteTopicById = ids => {
      const currentList = taskList.value.filter(
        item => ids.indexOf(item.topic_id) !== -1
      )
      let list = []
      currentList.forEach(current => {
        // 举一反三的题，直接删除
        if (current.relation_id) {
          list = taskList.value.filter(
            item => ids.indexOf(item.topic_id) === -1
          )
        } else {
          // 原题，则需要删除当前题目及与之关联的题目
          list = taskList.value.filter(
            item =>
              ids.indexOf(item.topic_id) === -1 &&
              ids.indexOf(item.relation_id) === -1
          )
        }
      })
      taskList.value = list
      postAddTaskInfo()
    }

    const reset = async () => {
      iframeTaskMitt.emit('delete-topic', taskList.value)
      taskList.value = []
      await postAddTaskInfo()
    }

    const resetAll = list => {
      taskList.value = list
      postAddTaskInfo()
    }

    const isExistBasket = id =>
      taskList.value.findIndex(item => item.topic_id === id) !== -1

    // 向对应的学段&学科篮子更新试题
    const postAddTaskInfo = async () => {
      let { userInfo, nowGlobalSubjectId, nowGlobalStageId } = JSON.parse(
        localStorage.getItem('auth')
      )
      let ids = []
      // 保证原题后面跟着举一反三的题
      for (let index = 0; index < taskList.value.length; index++) {
        const current = taskList.value[index]
        // 原题
        if (!current.relation_id) {
          ids.push({
            question_id: current.topic_id,
            is_similar: 0,
            relation_id: 0,
            set_total_score: current.totalScore,
            score_strategy: current.score_strategy,
            children_question: current.subScore?.map(item => ({
              question_id: item.id,
              set_total_score: item.score,
              score_strategy: item.score_strategy
            }))
          })
          // 找相似题
          const filtered = taskList.value.filter(item => {
            return item.relation_id && item.relation_id === current.topic_id
          })
          ids.push(
            ...filtered.map(item => ({
              question_id: item.topic_id,
              is_similar: 1,
              relation_id: current.topic_id,
              set_total_score: item.totalScore,
              score_strategy: item.score_strategy,
              children_question: item.subScore?.map(it => ({
                question_id: it.id,
                set_total_score: it.score,
                score_strategy: it.score_strategy
              }))
            }))
          )
        }
      }
      await postAddTask({
        user_id: userInfo.userId,
        stage: nowGlobalStageId,
        subject_id: nowGlobalSubjectId,
        question_ids: ids
      })
      postMessage()
    }

    // 根据学段&科目获取试题篮数据重置
    const getBasketQuestionInfo = async () => {
      let { userInfo, nowGlobalSubjectId, nowGlobalStageId } = JSON.parse(
        localStorage.getItem('auth')
      )

      const res = await getBasketQuestion({
        user_id: userInfo.userId,
        stage: nowGlobalStageId,
        subject_id: nowGlobalSubjectId
      })
      let list = res.data || []
      console.log('getBasket', list)
      list = list.map(question => ({
        score_strategy: question.score_strategy,
        totalScore: question.set_total_score,
        subScore: (question.children_question || []).map(item => ({
          id: item.question_id,
          score: item.set_total_score,
          score_strategy: item.score_strategy
        })),
        source: question.question_detail.source,
        subject_id: question.question_detail.subject,
        topic_id: question.question_detail.id,
        topic_type: question.question_detail.type,
        question_detail: question.question_detail,
        relation_id: question.relation_id, // 根据是否有关联id来判断是否为相似题
        is_similar: question.relation_id ? 1 : 0
      }))
      taskList.value = list
    }

    // 设置分数后更新takeList
    const updateTakeList = list => {
      console.log(list)
      taskList.value = taskList.value.map(item => {
        let temp = list.find(it => it.topic_id === item.topic_id)
        if (temp) {
          item.totalScore = temp.totalScore
          item.score_strategy = temp.score_strategy
          item.subScore = temp.subScore
        }
        return item
      })
      postAddTaskInfo()
    }

    getBasketQuestionInfo()
    return {
      taskList,

      setTaskList,
      reset,
      onDeleteTopic,
      deleteTopicById,
      resetAll,
      getBasketQuestionInfo,
      isExistBasket,
      createBroadcastChannel,
      destroyBroadcastChannel,
      updateTakeList
    }
  },
  {
    persist: true
  }
)

export const TaskTypeMap = {
  1: {
    text: '布置课程任务',
    title: '课程'
  },
  2: {
    text: '布置习题任务',
    title: '习题'
  },
  3: {
    text: '',
    title: '举一反三'
  },
  4: {
    text: '布置错题任务',
    title: '错题'
  }
}
